package com.mgee.netty.server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.protobuf.Any;
import com.mgee.netty.server.netty.IoSession;
import com.mgee.netty.server.netty.SessionManager;
import com.mgee.netty.server.pojo.ChatUserInfo;
import com.mgee.netty.server.protobuf.ImProto.ImMsg;
import com.mgee.netty.server.protobuf.ImProto.UserloginRequest;
import com.mgee.netty.server.protobuf.ImProto.UserloginRsp;
import com.mgee.netty.server.service.LoginService;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录相关服务实现类
 * @author mileswan
 *
 */
@Service("LoginFlightServiceImpl")
@Slf4j
public class LoginFlightServiceImpl implements LoginService {
	
	@Autowired
	private SessionManager sessionManager;
	
	@Override
	public void doLogin(ImMsg imMsg, IoSession currSession) {
		
		try {
			UserloginRequest loginRequest = imMsg.getMsg().unpack(UserloginRequest.class);
			String senderUsername = loginRequest.getUsername();
			String errDesc = "";
			//验证登录信息
			boolean isLoginSuccess = authenticate(senderUsername, loginRequest);
			sessionManager.setUserLogin(senderUsername, isLoginSuccess);
			if(isLoginSuccess) {
				//如果用户已在缓存
				IoSession existSession = SessionManager.userId2Sessions.get(senderUsername);
				ChatUserInfo sender;
				if(existSession != null && existSession.getUser() != null && senderUsername.equals(existSession.getUser().getUid())) {
					sender = existSession.getUser();
				}else {//如果用户还没有注册在缓存，则执行以下部分进行注册
					sender = new ChatUserInfo();
					sender.setUid(senderUsername);
					sender.setUsername(senderUsername);
					sender.setPassowrd(loginRequest.getPassword());
				}
				
//				if(loginRequest.getPlayerPack() != null) {
//					PlayerPack.Builder playerPackBuilder = PlayerPack.newBuilder();
//					playerPackBuilder.setUid(sender_uid);
//					playerPackBuilder.setNickName(loginRequest.getPlayerPack().getNickName());
//					playerPackBuilder.setChatno(loginRequest.getPlayerPack().getChatno());
//					playerPackBuilder.setRoleInfo(loginRequest.getPlayerPack().getRoleInfo());
//					
//					sender.setPlayerPack(playerPackBuilder.build());
//				}
				errDesc = "登录成功！";
				isLoginSuccess = sessionManager.registerSession(sender, currSession);
				if(!isLoginSuccess) {
					errDesc = "登录失败，用户已在其他设备登录！";
				}
			}else {
				errDesc = "登录验证失败！";
				log.info("用户"+ senderUsername +"的登录验证失败！");
			}
			
	    	// 按照定义的数据结构，创建登录返回消息对象  
			ImMsg responseMsg = buildResponse(imMsg, isLoginSuccess, errDesc);
	        //发送反馈消息
	        currSession.sendMessage(responseMsg);
	        
		}catch(Exception e) {
			log.error("用户登录验证时发生异常, ", e);
		}
		
	}

    /**
     * 验证登录请求
     * @param loginRequest
     * @return
     */
    private boolean authenticate(String uid, UserloginRequest loginRequest) {
		return true;
    	
    }
    
    /**
     * 构建登录返回消息体
     * @param gameMsg
     * @param isSuccess
     * @param errDesc
     * @return
     */
    private ImMsg buildResponse(ImMsg imMsg, boolean isSuccess, String errDesc) {
    	try {
    		UserloginRsp.Builder loginResponseBuilder = UserloginRsp.newBuilder();
    		ImMsg.Builder imMsgBuilder = ImMsg.newBuilder();
            
            loginResponseBuilder.setResult(isSuccess);
            loginResponseBuilder.setDescription(errDesc);
            UserloginRsp loginResponse = loginResponseBuilder.build();
            
            imMsgBuilder.setMsg(Any.pack(loginResponse));
            imMsgBuilder.setId(imMsg.getId());
            
            return imMsgBuilder.build();
    	}catch(Exception e) {
    		log.error("构建登录返回消息体时发生异常：", e);
    		return null;
    	}
    }

	@Override
	public void doLogout(ImMsg imMsg, IoSession currSession) {
		
		sessionManager.unregisterUserContext(currSession);
	}
}
